import os
import time
from datetime import timedelta

from flask import Flask, render_template, request, jsonify, send_from_directory

import curve

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
# 设置静态文件缓存过期时间
app.send_file_max_age_default = timedelta(seconds=1)

# 设置允许的文件格式
ALLOWED_EXTENSIONS = {'png', 'PNG'}


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


@app.route('/')
def hello_world():
    return 'Hello World!'


@app.route('/curvePro', methods=['POST', "GET"])
def curvePro():
    if request.method == 'POST':
        f = request.files['file']

        if not (f and allowed_file(f.filename)):
            return jsonify({"error": 1001, "msg": "请检查上传的图片类型，仅限于png、PNG"})

        polynomial_order = request.form.get("order")

        base_path = os.path.dirname(__file__)

        save_path = os.path.join(base_path, 'static/images', 'progress.png')
        f.save(save_path)

        polynomial, lua_expression = curve.parse_curve(polynomial_order)

        return render_template('progress.html', order=polynomial_order, polynomial=polynomial,
                               lua_expression=lua_expression, val1=time.time())

    return render_template("curvePro.html")


@app.route('/shutdown')
def shutdown():
    func = request.environ.get('werkzeug.server.shutdown')
    func()
    return 'Server shutting down'


@app.route('/download/<name>')
def ppt(name):
    file_name = "校招宣讲-2020.pptx"
    if name == "video":
        file_name = "NhaTrang.mp4"

    return send_from_directory("/root/curvePro/static", filename=file_name, as_attachment=True)

if __name__ == '__main__':
    app.run()
